package com.st.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent se)  { 
    	// Session 对象创建完成后
    	System.out.println("session创建");
    	
    	// 又来了一个新用户，获取Applic
    	HttpSession session = se.getSession();
    	ServletContext app = session.getServletContext();
    	
    	int onlineCount = (int) app.getAttribute("onlineCount");
    	// 数量+1
    	onlineCount ++;
    	// 再把数量写回去
    	app.setAttribute("onlineCount", onlineCount);
    }

    public void sessionDestroyed(HttpSessionEvent se)  { 
    	// 对象销毁
    	System.out.println("session销毁");
    	
    	// 又走了一个
    	HttpSession session = se.getSession();
    	ServletContext app = session.getServletContext();
    	
    	int onlineCount = (int) app.getAttribute("onlineCount");
    	// 数量-1
    	onlineCount --;
    	// 再把数量写回去
    	app.setAttribute("onlineCount", onlineCount);
    }
	
}
